package androidx.lifecycle.compose.samples

import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.*
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.LifecycleStartEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*

// 简单导航状态管理
sealed class Screen {
    object Home : Screen()
    object StateFlowScreen : Screen()
    object FlowScreen : Screen()
    object EventEffectScreen : Screen()
    object StartEffectScreen : Screen()
    object ResumeEffectScreen : Screen()
}

// 模拟生命周期 - 只实现Lifecycle接口
class TeLifecycle : Lifecycle() {
    override var currentState: State = State.INITIALIZED
    private val observers = mutableListOf<LifecycleObserver>()
    // 添加一个属性来引用LifecycleOwner
    private var lifecycleOwner: LifecycleOwner? = null

    // 设置LifecycleOwner引用的方法
    fun setLifecycleOwner(owner: LifecycleOwner) {
        this.lifecycleOwner = owner
    }

    override fun addObserver(observer: LifecycleObserver) {
        observers.add(observer)
        // 通知新添加的观察者当前状态
        when (currentState) {
            State.CREATED -> {
                if (observer is LifecycleEventObserver) {
                    observer.onStateChanged(lifecycleOwner as LifecycleOwner, Lifecycle.Event.ON_CREATE)
                }
            }
            State.STARTED -> {
                if (observer is LifecycleEventObserver) {
                    observer.onStateChanged( lifecycleOwner as LifecycleOwner,  Lifecycle.Event.ON_CREATE)
                    observer.onStateChanged(lifecycleOwner as LifecycleOwner, Lifecycle.Event.ON_START)
                }
            }
            State.RESUMED -> {
                if (observer is LifecycleEventObserver) {
                    observer.onStateChanged(lifecycleOwner as LifecycleOwner, Lifecycle.Event.ON_CREATE)
                    observer.onStateChanged(lifecycleOwner as LifecycleOwner, Lifecycle.Event.ON_START)
                    observer.onStateChanged(lifecycleOwner as LifecycleOwner, Lifecycle.Event.ON_RESUME)
                }
            }
            else -> {}
        }
    }

    override fun removeObserver(observer: LifecycleObserver) {
        observers.remove(observer)
    }

    fun getCurrentState(): State {
        return currentState
    }

    fun pause() {
        if (currentState == State.RESUMED) {
            currentState = State.STARTED
            notifyEvent(Lifecycle.Event.ON_PAUSE)
        }
    }

    fun stop() {
        if (currentState == State.RESUMED) {
            pause()
        }
        if (currentState == State.STARTED) {
            currentState = State.CREATED
            notifyEvent(Lifecycle.Event.ON_STOP)
        }
    }

    fun start() {
        if (currentState == State.CREATED) {
            currentState = State.STARTED
            notifyEvent(Lifecycle.Event.ON_START)
        }
    }

    fun resume() {
        if (currentState == State.STARTED) {
            currentState = State.RESUMED
            notifyEvent(Lifecycle.Event.ON_RESUME)
        }
    }

    fun create() {
        if (currentState == State.INITIALIZED) {
            currentState = State.CREATED
            notifyEvent(Lifecycle.Event.ON_CREATE)
        }
    }

    private fun notifyEvent(event: Lifecycle.Event) {
        observers.forEach { observer ->
            if (observer is LifecycleEventObserver) {
                observer.onStateChanged(lifecycleOwner as LifecycleOwner, event)
            }
        }
    }
}

class TeLifecycleOwner(override val lifecycle: TeLifecycle) : LifecycleOwner {
    init {
        // 在构造函数中设置LifecycleOwner引用
        lifecycle.setLifecycleOwner(this)
    }

    fun getLifecycle(): Lifecycle {
        return lifecycle
    }
}

// 分析服务接口
interface TimeAnalytics {
    fun stopTimeTracking(): TimeAnalytics
}

interface DataAnalytics {
    fun trackScreenView(screenName: String)
    fun startTimeTracking(): TimeAnalytics
    fun sendDisposalAnalytics(timeAnalytics: TimeAnalytics)
}

// 分析服务实现
class SampleAnalyticsService : DataAnalytics, TimeAnalytics {
    override fun trackScreenView(screenName: String) {
        // 实现跟踪逻辑
    }

    override fun startTimeTracking(): TimeAnalytics {
        return this
    }

    override fun stopTimeTracking(): TimeAnalytics {
        return this
    }

    override fun sendDisposalAnalytics(timeAnalytics: TimeAnalytics) {
        // 实现分析数据发送
    }
}

// 辅助函数：为每个测试用例创建并初始化独立的生命周期实例
@Composable
private fun createAndInitializeLifecycleOwner(): TeLifecycleOwner {
    // 为每个测试用例创建独立的生命周期实例
    val lifecycle = remember { TeLifecycle() }
    val lifecycleOwner = remember { TeLifecycleOwner(lifecycle) }
    
    // 初始化生命周期
    LaunchedEffect(Unit) {
        lifecycle.create()
        lifecycle.start()
        lifecycle.resume()
    }
    
    // 当组件被移除时重置生命周期状态
    DisposableEffect(Unit) {
        onDispose {
            try {
                // 确保生命周期正确结束
                lifecycle.stop()
                lifecycle.destroy()
            } catch (e: Exception) {
                // 忽略可能的状态转换异常
            }
        }
    }
    
    return lifecycleOwner
}

// 主导航界面
@Composable
fun LifecycleComposeNavigationUI() {
    var currentScreen by remember { mutableStateOf<Screen>(Screen.Home) }
    // 移除共享的生命周期实例
    // val lifecycle = remember { TeLifecycle() }
    // val lifecycleOwner = remember { TeLifecycleOwner(lifecycle) }
    // 移除共享的生命周期初始化
    // LaunchedEffect(Unit) {
    //     lifecycle.create()
    //     lifecycle.start()
    //     lifecycle.resume()
    // }

    Column(modifier = Modifier.fillMaxSize()) {
        // 当前界面标题
        Text(
            text = when (currentScreen) {
                is Screen.Home -> "生命周期API示例导航"
                is Screen.StateFlowScreen -> "StateFlow collectAsStateWithLifecycle示例"
                is Screen.FlowScreen -> "Flow collectAsStateWithLifecycle示例"
                is Screen.EventEffectScreen -> "LifecycleEventEffect示例"
                is Screen.StartEffectScreen -> "LifecycleStartEffect示例"
                is Screen.ResumeEffectScreen -> "LifecycleResumeEffect示例"
            },
            modifier = Modifier.padding(16.dp)
        )

        // 显示当前界面内容
        when (currentScreen) {
            is Screen.Home -> HomeScreen(onNavigate = { currentScreen = it })
            // 为每个测试用例创建独立的生命周期实例
            is Screen.StateFlowScreen -> {
                val lifecycleOwner = createAndInitializeLifecycleOwner()
                StateFlowScreen(lifecycleOwner)
            }
            is Screen.FlowScreen -> {
                val lifecycleOwner = createAndInitializeLifecycleOwner()
                FlowScreen(lifecycleOwner)
            }
            is Screen.EventEffectScreen -> {
                val lifecycleOwner = createAndInitializeLifecycleOwner()
                EventEffectScreen(lifecycleOwner)
            }
            is Screen.StartEffectScreen -> {
                val lifecycleOwner = createAndInitializeLifecycleOwner()
                StartEffectScreen(lifecycleOwner)
            }
            is Screen.ResumeEffectScreen -> {
                val lifecycleOwner = createAndInitializeLifecycleOwner()
                ResumeEffectScreen(lifecycleOwner)
            }
        }

        // 导航栏（仅在非主界面显示返回按钮）
        if (currentScreen != Screen.Home) {
            Button(
                onClick = { currentScreen = Screen.Home },
                modifier = Modifier.padding(16.dp)
            ) {
                Text("返回主菜单")
            }
        }
    }
}

// 主菜单界面
@Composable
fun HomeScreen(onNavigate: (Screen) -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text(text = "选择要查看的生命周期API示例:")

        Button(onClick = { onNavigate(Screen.StateFlowScreen) }) {
            Text("StateFlow collectAsStateWithLifecycle")
        }

        Button(onClick = { onNavigate(Screen.FlowScreen) }) {
            Text("Flow collectAsStateWithLifecycle")
        }

        Button(onClick = { onNavigate(Screen.EventEffectScreen) }) {
            Text("LifecycleEventEffect")
        }

        Button(onClick = { onNavigate(Screen.StartEffectScreen) }) {
            Text("LifecycleStartEffect")
        }

        Button(onClick = { onNavigate(Screen.ResumeEffectScreen) }) {
            Text("LifecycleResumeEffect")
        }
    }
}

/**
 * ### 测试方法：
1.
   运行应用，进入StateFlowScreen界面
2.
   观察初始状态显示
3.
   依次点击不同的生命周期按钮：
   - 点击"Pause"按钮，状态应变为STARTED
   - 点击"Resume"按钮，状态应变为RESUMED
   - 点击"Stop"按钮，状态应变为CREATED
   - 点击"Start"按钮，状态应变为STARTED
4.
   在不同状态下点击"更新状态"按钮，观察UI更新行为
5.
   特别测试：在STOPPED状态（CREATED）更新状态，然后恢复STARTED状态，观察UI是否直接显示最新状态
 */
// StateFlow示例界面
@Composable
fun StateFlowScreen(lifecycleOwner: LifecycleOwner) {
    class ExampleState {
        private val _uiState = MutableStateFlow("初始状态")
        val uiState: StateFlow<String> = _uiState.asStateFlow()

        fun updateState(newState: String) {
            _uiState.value = newState
        }
    }

    val state = remember { ExampleState() }
    val uiState by state.uiState.collectAsStateWithLifecycle(lifecycleOwner = lifecycleOwner)
    val count = remember { mutableStateOf(0) }
    // 添加当前生命周期状态显示
    val currentState = remember { mutableStateOf("UNKNOWN") }

    // 监控生命周期状态变化
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { source: LifecycleOwner, event ->
            // 更新当前状态显示
            currentState.value = "${event.name} (${(lifecycleOwner.lifecycle as TeLifecycle).currentState})"
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        // 初始状态设置
        currentState.value = "初始状态: ${(lifecycleOwner.lifecycle as TeLifecycle).currentState}"

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text(text = "当前状态值: $uiState")
        Button(onClick = {
            count.value++
            state.updateState("更新后的状态 ${count.value}")
        }) {
            Text("更新状态")
        }
        Text(text = "StateFlow collectAsStateWithLifecycle 在组件处于STARTED或更高级别时自动收集数据")
        Text(text = "当前生命周期状态: ${currentState.value}")

        // 添加生命周期控制按钮，优化状态转换逻辑
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(onClick = {
                val lifecycle = (lifecycleOwner as TeLifecycleOwner).lifecycle
                // 无论当前状态如何，都尝试暂停
                if (lifecycle.currentState == Lifecycle.State.RESUMED) {
                    lifecycle.pause()
                } else {
                    // 先恢复再暂停，确保可以测试暂停状态
                    lifecycle.resume()
                    lifecycle.pause()
                }
            }) {
                Text("Pause")
            }
            Button(onClick = {
                (lifecycleOwner as TeLifecycleOwner).lifecycle.resume()
            }) {
                Text("Resume")
            }
            Button(onClick = {
                val lifecycle = (lifecycleOwner as TeLifecycleOwner).lifecycle
                // 无论当前状态如何，都尝试停止
                if (lifecycle.currentState == Lifecycle.State.STARTED) {
                    lifecycle.stop()
                } else if (lifecycle.currentState == Lifecycle.State.RESUMED) {
                    // 先暂停再停止
                    lifecycle.pause()
                    lifecycle.stop()
                }
            }) {
                Text("Stop")
            }
            Button(onClick = {
                val lifecycle = (lifecycleOwner as TeLifecycleOwner).lifecycle
                // 无论当前状态如何，都尝试启动
                if (lifecycle.currentState == Lifecycle.State.CREATED) {
                    lifecycle.start()
                } else if (lifecycle.currentState == Lifecycle.State.INITIALIZED) {
                    // 先创建再启动
                    lifecycle.create()
                    lifecycle.start()
                }
            }) {
                Text("Start")
            }
        }
    }
}

/**
 * ## 测试准备
1. 1.
   运行应用并从主菜单选择"Flow collectAsStateWithLifecycle"选项进入FlowScreen
## 具体测试步骤
### 1. 初始状态观察
- 进入界面后，观察计数器是否开始自动递增（每秒+1）
- 初始状态应为"Flow计数器值: 0"，然后每秒更新一次
### 2. 测试PAUSED状态
- 点击"Pause"按钮将组件置于PAUSED状态
- 观察计数器是否继续更新（在PAUSED状态下计数器应该 继续更新 ，因为collectAsStateWithLifecycle在STARTED及以上状态都工作）
- 注意：PAUSED仍属于STARTED级别，所以数据流不会暂停
### 3. 测试STOPPED状态
- 点击"Stop"按钮将组件置于STOPPED状态
- 观察计数器是否停止更新（在STOPPED状态下计数器应该 停止更新 ）
- 让应用保持在STOPPED状态几秒钟
### 4. 测试恢复STARTED状态
- 点击"Start"按钮将组件从STOPPED状态恢复到STARTED状态
- 观察计数器是否立即更新到最新值（而不是显示中间错过的所有值）
### 5. 测试RESUMED状态
- 点击"Resume"按钮将组件置于RESUMED状态
- 确认计数器继续正常更新
### 6. 完整生命周期循环测试
- 按照 STOP → START → PAUSE → RESUME 的顺序点击按钮
- 验证每个状态转换时计数器的行为是否符合预期
## 预期行为
- 在STARTED或RESUMED状态下：计数器每秒正常递增
- 在STOPPED状态下：计数器停止更新
- 从STOPPED恢复到STARTED状态时：UI应直接显示最新的计数器值
## 测试要点
- 重点验证在STOPPED状态下数据流是否真正暂停（计数器停止）
- 验证从STOPPED恢复时是否直接显示最新值，而不是重放所有中间值
- 确认生命周期控制按钮能正确改变组件状态
 */
// Flow示例界面
@Composable
fun FlowScreen(lifecycleOwner: LifecycleOwner) {
    class ExampleState {
        val counter = flow {
            var count = 0
            while (count < 100) { // 限制循环次数避免无限循环
                emit(count++)
                delay(1000)
            }
        }
    }

    val state = remember { ExampleState() }
    val count by state.counter.collectAsStateWithLifecycle(
        initialValue = 0,
        lifecycleOwner = lifecycleOwner
    )

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text(text = "Flow计数器值: $count")
        Text(text = "Flow collectAsStateWithLifecycle 每秒更新一次计数")
        Text(text = "当组件进入STOPPED状态时，收集将暂停")

        // 添加生命周期控制按钮，用于测试不同生命周期状态下的行为
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(onClick = { (lifecycleOwner as TeLifecycleOwner).lifecycle.pause() }) {
                Text("Pause")
            }
            Button(onClick = { (lifecycleOwner as TeLifecycleOwner).lifecycle.resume() }) {
                Text("Resume")
            }
            Button(onClick = { (lifecycleOwner as TeLifecycleOwner).lifecycle.stop() }) {
                Text("Stop")
            }
            Button(onClick = { (lifecycleOwner as TeLifecycleOwner).lifecycle.start() }) {
                Text("Start")
            }
        }
    }
}

// LifecycleEventEffect示例界面 - 直接使用LifecycleEventEffect API

/**
 * ## 测试准备
1. 1.
   运行应用并从主菜单选择"LifecycleEventEffect"选项进入EventEffectScreen
## 具体测试步骤
### 1. 初始状态观察
- 进入界面后，观察事件日志列表中是否有初始事件记录
- 注意当前界面应显示"LifecycleEventEffect 示例"标题和事件日志列表
### 2. 测试RESUMED状态事件
- 当前组件应处于RESUMED状态，确认日志中是否有"触发了 ON_RESUME 事件，记录屏幕浏览"的记录
### 3. 测试PAUSED状态
- 点击"Pause"按钮将组件置于PAUSED状态
- 观察事件日志中是否新增"触发了 ON_PAUSE 事件"的记录
### 4. 测试恢复RESUMED状态
- 点击"Resume"按钮将组件从PAUSED状态恢复到RESUMED状态
- 观察事件日志中是否再次新增"触发了 ON_RESUME 事件，记录屏幕浏览"的记录
### 5. 测试STOPPED状态
- 点击"Stop"按钮将组件置于STOPPED状态
- 首先应看到"触发了 ON_PAUSE 事件"的记录（因为从RESUMED到STOPPED必须经过PAUSED）
- 然后应看到"触发了 ON_STOP 事件"的记录
### 6. 测试STARTED状态
- 点击"Start"按钮将组件从STOPPED状态恢复到STARTED状态
- 观察事件日志中是否新增"触发了 ON_START 事件"的记录
### 7. 测试完整生命周期转换
- 执行一系列状态转换，如：RESUME → PAUSE → RESUME → PAUSE → STOP → START → RESUME
- 验证每个转换对应的事件是否都被正确记录
## 预期行为
- 每当组件进入对应生命周期状态时，LifecycleEventEffect会触发相应的回调函数
- 事件日志列表会按时间顺序记录所有触发的事件
- 每个事件都应该与正确的生命周期转换相对应
## 测试要点
- 验证ON_RESUME、ON_PAUSE、ON_START和ON_STOP四个主要事件是否正确触发
- 确认生命周期状态转换的顺序是否符合Android标准（如从RESUMED到STOPPED必须先经过PAUSED）
- 验证多次触发同一状态转换时，事件是否被重复记录
- 测试从不同状态恢复时，事件触发是否符合预期（如从STOPPED恢复只会触发ON_START，而不是ON_RESUME）
 */
@Composable
fun EventEffectScreen(lifecycleOwner: LifecycleOwner) {
    val events = remember { mutableStateListOf<String>() }
    val analyticsService = remember { SampleAnalyticsService() }

    // 直接使用LifecycleEventEffect API
    LifecycleEventEffect(Lifecycle.Event.ON_RESUME, lifecycleOwner) {
        events.add("触发了 ON_RESUME 事件，记录屏幕浏览")
        analyticsService.trackScreenView("EventEffectScreen")
    }

    // 添加其他事件的监听以展示效果
    LifecycleEventEffect(Lifecycle.Event.ON_PAUSE, lifecycleOwner) {
        events.add("触发了 ON_PAUSE 事件")
    }

    LifecycleEventEffect(Lifecycle.Event.ON_START, lifecycleOwner) {
        events.add("触发了 ON_START 事件")
    }

    LifecycleEventEffect(Lifecycle.Event.ON_STOP, lifecycleOwner) {
        events.add("触发了 ON_STOP 事件")
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text(text = "LifecycleEventEffect 示例")
        Text(text = "当组件触发特定生命周期事件时执行代码")

        androidx.compose.foundation.lazy.LazyColumn(modifier = Modifier.weight(1f)) {
            items(events.size) { index ->
                Text(text = events[index])
            }
        }

        // 添加生命周期控制按钮
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(onClick = { (lifecycleOwner as TeLifecycleOwner).lifecycle.pause() }) {
                Text("Pause")
            }
            Button(onClick = { (lifecycleOwner as TeLifecycleOwner).lifecycle.resume() }) {
                Text("Resume")
            }
            Button(onClick = { (lifecycleOwner as TeLifecycleOwner).lifecycle.stop() }) {
                Text("Stop")
            }
            Button(onClick = { (lifecycleOwner as TeLifecycleOwner).lifecycle.start() }) {
                Text("Start")
            }
        }
    }
}

// LifecycleStartEffect示例界面
@Composable
fun StartEffectScreen(lifecycleOwner: LifecycleOwner) {
    val events = remember { mutableStateListOf<String>() }
    val analyticsService = remember { SampleAnalyticsService() }
    val isActive = remember { mutableStateOf(false) }
    val timeTracker = remember { mutableStateOf<TimeAnalytics?>(null) }
    // 添加一个状态来显示当前生命周期状态
    val currentLifecycleState = remember { mutableStateOf("UNKNOWN") }

    // 直接使用LifecycleStartEffect API，不再使用DisposableEffect模拟
    LifecycleStartEffect(key1 = Unit, lifecycleOwner = lifecycleOwner) { // 添加了 key1 = Unit        // 进入STARTED状态时执行
        isActive.value = true
        timeTracker.value = analyticsService.startTimeTracking()
        events.add("组件进入STARTED状态，开始时间追踪")

        onStopOrDispose {
            // 进入STOPPED状态或组件销毁时执行
            isActive.value = false
            timeTracker.value?.stopTimeTracking()
            events.add("组件进入STOPPED状态或销毁，停止时间追踪")
        }
    }

    // 为了显示生命周期状态变化，仍然保留对生命周期事件的监控
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { source: LifecycleOwner, event ->
            // 更新当前生命周期状态显示
            currentLifecycleState.value = event.name
            // 记录其他事件，帮助调试
            events.add("触发了 ${event.name} 事件")
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        // 初始记录当前状态
        val initialState = (lifecycleOwner.lifecycle as TeLifecycle).currentState
        currentLifecycleState.value = initialState.name
        events.add("初始生命周期状态: $initialState")

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text(text = "LifecycleStartEffect 示例")
        Text(text = "状态: ${if (isActive.value) "Active" else "Inactive"}")
        Text(text = "当前生命周期状态: ${currentLifecycleState.value}")
        Text(text = "在组件进入STARTED状态时开始时间追踪，在STOPPED状态时停止")

        androidx.compose.foundation.lazy.LazyColumn(modifier = Modifier.weight(1f)) {
            items(events.size) { index ->
                Text(text = events[index])
            }
        }

        // 添加完整的生命周期控制按钮，方便测试各种状态转换
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(onClick = {
                (lifecycleOwner as TeLifecycleOwner).lifecycle.stop()
                events.add("手动调用 stop()")
            }) {
                Text("Stop")
            }
            Button(onClick = {
                (lifecycleOwner as TeLifecycleOwner).lifecycle.start()
                events.add("手动调用 start()")
            }) {
                Text("Start")
            }
            Button(onClick = {
                (lifecycleOwner as TeLifecycleOwner).lifecycle.pause()
                events.add("手动调用 pause()")
            }) {
                Text("Pause")
            }
            Button(onClick = {
                (lifecycleOwner as TeLifecycleOwner).lifecycle.resume()
                events.add("手动调用 resume()")
            }) {
                Text("Resume")
            }
        }
    }
}

// LifecycleResumeEffect示例界面
// LifecycleResumeEffect示例界面
@Composable
fun ResumeEffectScreen(lifecycleOwner: LifecycleOwner) {
    val events = remember { mutableStateListOf<String>() }
    val analyticsService = remember { SampleAnalyticsService() }
    val isActive = remember { mutableStateOf(false) }
    val timeTracker = remember { mutableStateOf<TimeAnalytics?>(null) }

    // 使用真实的LifecycleResumeEffect API
    LifecycleResumeEffect(key1 = Unit, lifecycleOwner = lifecycleOwner) {
        // 进入RESUMED状态时执行
        isActive.value = true
        timeTracker.value = analyticsService.startTimeTracking()
        events.add("组件进入RESUMED状态，开始时间追踪")

        onPauseOrDispose {
            // 进入PAUSED状态或组件销毁时执行
            isActive.value = false
            timeTracker.value?.stopTimeTracking()
            events.add("组件进入PAUSED状态或销毁，停止时间追踪")
        }
    }

    // 为了显示生命周期状态变化，保留对生命周期事件的监控
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { source: LifecycleOwner, event ->
            // 记录其他事件，帮助调试
            if (event == Lifecycle.Event.ON_RESUME || event == Lifecycle.Event.ON_PAUSE) {
                events.add("触发了 ${event.name} 事件")
            }
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text(text = "LifecycleResumeEffect 示例")
        Text(text = "状态: ${if (isActive.value) "Active" else "Inactive"}")
        Text(text = "在组件进入RESUMED状态时开始时间追踪，在PAUSED状态时停止")

        androidx.compose.foundation.lazy.LazyColumn(modifier = Modifier.weight(1f)) {
            items(events.size) { index ->
                Text(text = events[index])
            }
        }

        // 添加生命周期控制按钮
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(onClick = { (lifecycleOwner as TeLifecycleOwner).lifecycle.pause() }) {
                Text("Pause")
            }
            Button(onClick = { (lifecycleOwner as TeLifecycleOwner).lifecycle.resume() }) {
                Text("Resume")
            }
        }
    }
}